// components/OnlineCollecting/DictComboboxSelect.tsx
import React, { useState, useEffect } from 'react';
import { Select, message } from 'antd';
import { dictData } from '@/services/prefiling/onlineCollecting';

interface DictComboboxSelectProps {
  dictCode: string;
  defaultValue?: string;
  onChange?: (value: string) => void;
  className?: string;
  style?: React.CSSProperties;
  placeholder?: string;
}

const DictComboboxSelect: React.FC<DictComboboxSelectProps> = ({
  dictCode,
  defaultValue, 
  onChange,
  className,
  style,
  placeholder
}) => {
  const [options, setOptions] = useState<Array<{ label: string; value: string }>>([]);
  const [loading, setLoading] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const [selectedValue, setSelectedValue] = useState(defaultValue); // 内部状态管理选中值
console.log(defaultValue)
  // 同步外部propValue到内部状态
  useEffect(() => {
    setSelectedValue(defaultValue);
  }, [defaultValue]);

  useEffect(() => {
    const fetchDictData = async () => {
      try {
        setLoading(true);
        const res = await dictData({ dictType: dictCode });
        
        if (res && Array.isArray(res)) {
          let newOptions = res.map(item => ({
            label: item.label,
            value: item.label
          }));

          // 检查propValue是否在选项中，如果不在则添加

          if (defaultValue && !newOptions.some(opt => opt.label === defaultValue)) {
            newOptions = [...newOptions, {
              label: defaultValue,
              value: defaultValue
            }];
          }

          setOptions(newOptions);
        }
      } catch (error) {
        console.error('加载字典数据失败:', error);
        message.error('加载字典数据失败');
      } finally {
        setLoading(false);
      }
    };

    fetchDictData();
  }, [dictCode, defaultValue]);

  const handleSearch = (value: string) => {
    setSearchValue(value);
  };

  const handleChange = (value: string) => {
    setSelectedValue(value); // 更新内部状态
    if (onChange) {
      onChange(value); // 通知父组件
    }
  };

  const handleCreate = () => {
    if (!searchValue.trim()) return;

    const newOption = {
      label: searchValue,
      value: searchValue
    };

    // 如果选项不存在则添加
    if (!options.some(opt => opt.value === searchValue)) {
      setOptions(prev => [...prev, newOption]);
    }

    // 选中新创建的值
    handleChange(searchValue);
  };

  return (
    <Select
      className={className}
      style={style}
      placeholder={placeholder}
      showSearch
      allowClear
      loading={loading}
      value={selectedValue}  // 使用内部状态管理选中值
      onChange={handleChange}
      onSearch={handleSearch}
      filterOption={(input, option) =>
        (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
      }
      options={options}
      onBlur={() => {
        if (searchValue && !options.some(opt => opt.value === searchValue)) {
          handleCreate();
        }
      }}
      dropdownRender={menu => (
        <>
          {menu}
          {searchValue && !options.some(opt => opt.value === searchValue) && (
            <div 
              style={{ 
                padding: '8px', 
                cursor: 'pointer',
                borderTop: '1px solid #f0f0f0'
              }}
              onClick={handleCreate}
            >
              使用自定义值: "{searchValue}"
            </div>
          )}
        </>
      )}
    />
  );
};

export default DictComboboxSelect;